package com.df.my_net_game.game_rpc.client;

import com.df.my_net_game.game_rpc.GRpcHeader;
import com.df.my_net_game.game_rpc.EzGameMsg;
import com.df.my_net_game.game_rpc.ServerNode;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ChannelHandler.Sharable
public class GRpcClientHandler  extends SimpleChannelInboundHandler<EzGameMsg> {
    ServerNode serverNode;

    public GRpcClientHandler(ServerNode serverNode) {
        this.serverNode = serverNode;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, EzGameMsg msg) {
        GRpcHeader header = msg.getHeader();
        Integer msgType = header.getMsgType();
        if(msgType.equals(1)){
            log.error("接收到请求消息，放弃处理，请求者："+serverNode.getServiceName());
            return;
        }
//        Long reqId = header.getReqId();
//        Promise<EzGameMsg> gRpcMsgPromise = serverNode.getReqCache().remove(reqId);
//        if(gRpcMsgPromise != null){
//            gRpcMsgPromise.trySuccess(msg);
//        }else {//TODO 返回不存在的消息id，直接抛弃？
//
//        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("RPC client exception", cause);
        //
        ctx.close();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.warn("Connection lost, trying to reconnect...");
        //TODO 检查是手动断开还是异常断开，异常断开则实现重连逻辑
        super.channelInactive(ctx);
    }
}
